/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * jifRegistrarComprobanteDeOrden.java
 *
 * Created on 03-ago-2010, 14:49:49
 */

package Comprobantes;

import administracion.delegate.GestionPedidosDelegate;
import administracion.helper.Listas;
import administracion.helper.Utiles_Fecha;
import administracion.helper.Utiles_MensajesDialogo;
import administracion.helper.Utiles_Validar;
import administracion.helper.VerificarDatos;
import administracion.propiedades.Propiedades;
import com.jidesoft.hints.ListDataIntelliHints;
import Utiles.ExampleFileFilter;
import Utiles.IFrameBusqueda;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JFormattedTextField;
import javax.swing.JList;
import javax.swing.text.MaskFormatter;
import suministros.ejb30.TO.EmpresaTO;
import suministros.ejb30.TO.OrdenTO;
import suministros.ejb30.TO.ProveedorTO;
import suministros.ejb30.TO.SimpleEntidadTO;
import suministros.ejb30.TO.TipoTO;

import suministros.ejb30.entity.ComprobantePago;
import suministros.ejb30.entity.Parametros;
import suministros.ejb30.entity.Tipo;
import suministros.ejb30.entity.TipoCambioDiario;
import suministros.ejb30.helper.Utiles_Convertir;


/**
 *
 * @author Luis_Angel
 */
public class jifRegistrarComprobanteDeOrden extends javax.swing.JInternalFrame implements IFrameBusqueda{
     private MaskFormatter mascaraFechaIngreso;
     private boolean isExisteOrden;
     private OrdenTO orden;
     private byte[] archivo;
     private JFileChooser file;
     private ExampleFileFilter filter;
     private String id_empresa;
     private ListDataIntelliHints intelliHintsOrdenes;
    /** Creates new form jifRegistrarComprobanteDeOrden */
    public jifRegistrarComprobanteDeOrden() {
        construirMascaras();
        initComponents();
       // jpDescripcion.setVisible(false);
       // pack();
        List empresasss = Listas.getEmpresas();
        if(empresasss.isEmpty()){
            this.jCheckBox1.setEnabled(false);
        }
         try {
            cargaHintsIndependientes();
        } catch (Exception ex) {
        }
        llenarComboEmpresa();
        llenarComboTipoComprobante();
       

         Utiles_Validar.validaCaracteres(this.jtfFactura,4);
         Utiles_Validar.validaCaracteres(this.jtfNumero,8);
    }
    private void construirMascaras() {
        try {
          this.mascaraFechaIngreso = new MaskFormatter("##/##/####");
        } catch (ParseException ex) {
          Logger.getLogger(jifRegistrarComprobanteDeOrden.class.getName()).log(Level.SEVERE, null, ex);
          ex.printStackTrace();
        }
        
    }

      private void cargaHintsIndependientes() throws Exception {

        List<OrdenTO> lista = GestionPedidosDelegate.getInstance().getOrdenesSinComprobante(Listas.getZonas(), this.id_empresa);
        this.intelliHintsOrdenes = new ListDataIntelliHints(this.jtfOrden,lista );
        ((JList) this.intelliHintsOrdenes.getDelegateComponent()).setFixedCellWidth(200);


    }

     private void llenarComboTipoComprobante() {
        List listaTipos1 = null;
        List listaTipos_cbo1 = this.cboBeanBindingTipo1.getLista();
        listaTipos_cbo1.clear();
        try
        {
          listaTipos1 = Listas.getTipo_porTabla("tipo_Documento");

          this.cboBeanBindingTipo1.setLista(listaTipos1);
          this.bindingGroup.bind();
          this.jcboComprobante.updateUI();
          this.jcboComprobante.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener Comprobantes de Pago\n" + ex.getMessage());
          ex.printStackTrace();
          Logger.getLogger(jifConsultarComprobante.class.getName()).log(Level.SEVERE, null, ex);
        }
      }

     private void agregaEventos(){
      /*  this.jtfOrden.addKeyListener(new KeyAdapter(){
                public void keyReleased(KeyEvent e){
                    if(jtfOrden.getText().trim().length()>0)

                    else

                }
            });*/

     }

      private void llenarComboEmpresa() {
        List empresas = null;
        List listaPaises_cbo = this.cboBeanBindingEmpresa1.getLista();
        listaPaises_cbo.clear();
        try
        {
          if(this.jCheckBox1.isSelected()){
                empresas = Listas.getEmpresas();
            }
            else{
                empresas = Listas.getEmpresaPrincipal();
            }
          this.cboBeanBindingEmpresa1.setLista(empresas);
          this.bindingGroup.bind();
          this.jcbEmpresa.updateUI();
          this.jcbEmpresa.setSelectedIndex(0);
        } catch (Exception ex) {
          Utiles_MensajesDialogo.mensajeAlerta("Error al obtener empresas\n" + ex.getMessage());
          ex.printStackTrace();

        }
      }
      
    private String verificar(){
        boolean retorno = false;
        String mensaje="";
         if(!this.isExisteOrden)
            mensaje+="Escoja una orden valida\n";
        if(this.jtfOrden.getText().trim().length()==0)
            mensaje+="Escoja una orden\n";
        if(this.jtfMonto.getText().trim().length()==0)
            mensaje+="Ingrese un monto\n";
        if(this.jtfMonto.getText().trim().length()==0)
            mensaje+="Ingrese una serie\n";
        if(this.jtfMonto.getText().trim().length()==0)
            mensaje+="Ingrese un numero\n";
        if(this.jtfMonto.getText().trim().equalsIgnoreCase("/ /"))
            mensaje+="Ingrese una fecha\n";
        try{
             Date fecha = new Date(VerificarDatos.verificaFecha(this.jftfFechaRegistro.getText().trim()).getTime());
             Date fecha_emision = new Date(VerificarDatos.verificaFecha(this.orden.getFecha_emision()).getTime());
             if(fecha.before(fecha_emision)){
                mensaje+="fecha inferior a la emitida\n";
        }
        }catch(Exception e){
            mensaje+="fecha invalida";
        }

        return mensaje;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        cboBeanBindingTipo1 = new administracion.BeanBinding.CboBeanBindingTipo();
        cboBeanBindingEmpresa1 = new administracion.BeanBinding.CboBeanBindingEmpresa();
        jPanel1 = new javax.swing.JPanel();
        jtfOrden = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jtfFactura = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jftfFechaRegistro = new JFormattedTextField(this.mascaraFechaIngreso);
        jLabel3 = new javax.swing.JLabel();
        jtfNumero = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jcbEmpresa = new javax.swing.JComboBox();
        jLabel20 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jlblArchivo = new javax.swing.JLabel();
        jpDescripcion = new javax.swing.JPanel();
        jlblDescripcion = new javax.swing.JLabel();
        jlblDescripcion1 = new javax.swing.JLabel();
        jlblDescripcion2 = new javax.swing.JLabel();
        jlblDescripcion3 = new javax.swing.JLabel();
        jlblDescripcion4 = new javax.swing.JLabel();
        jlblDescripcion5 = new javax.swing.JLabel();
        jlblDescripcion6 = new javax.swing.JLabel();
        jCheckBox1 = new javax.swing.JCheckBox();
        jLabel24 = new javax.swing.JLabel();
        jcboComprobante = new javax.swing.JComboBox();
        jLabel25 = new javax.swing.JLabel();
        jtfMonto = new javax.swing.JTextField();
        jbAceptar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();

        setIconifiable(true);
        setTitle("Registrar Comprobante de Orden");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        jtfOrden.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfOrdenActionPerformed(evt);
            }
        });
        jtfOrden.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtfOrdenKeyPressed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel1.setText("NRO. ORDEN");

        jLabel2.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel2.setText("SERIE");

        jtfFactura.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfFacturaActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel4.setText("DOCUMENTO");

        jftfFechaRegistro.setToolTipText("Fecha del pedido");
        jftfFechaRegistro.setFont(new java.awt.Font("Arial", 0, 12));
        jftfFechaRegistro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jftfFechaRegistroActionPerformed(evt);
            }
        });
        jftfFechaRegistro.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jftfFechaRegistroKeyPressed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel3.setText("NUMERO");

        jtfNumero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfNumeroActionPerformed(evt);
            }
        });

        jButton1.setText("Seleccionar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jcbEmpresa.setEnabled(false);

        org.jdesktop.beansbinding.ELProperty eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingEmpresa1, eLProperty, jcbEmpresa);
        bindingGroup.addBinding(jComboBoxBinding);

        jcbEmpresa.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcbEmpresaItemStateChanged(evt);
            }
        });

        jLabel20.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel20.setText("EMPRESA");

        jLabel5.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel5.setText("FECHA ");

        jlblArchivo.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        jpDescripcion.setVisible(false);
        pack();
        jpDescripcion.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jlblDescripcion.setFont(new java.awt.Font("Arial", 1, 10));
        jpDescripcion.add(jlblDescripcion, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 0, 350, 20));

        jlblDescripcion1.setFont(new java.awt.Font("Arial", 1, 10));
        jpDescripcion.add(jlblDescripcion1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 350, 20));

        jlblDescripcion2.setFont(new java.awt.Font("Arial", 1, 10));
        jpDescripcion.add(jlblDescripcion2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 350, 20));

        jlblDescripcion3.setFont(new java.awt.Font("Arial", 1, 10));
        jpDescripcion.add(jlblDescripcion3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 60, 350, 20));

        jlblDescripcion4.setFont(new java.awt.Font("Arial", 1, 10));
        jpDescripcion.add(jlblDescripcion4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 80, 340, 20));
        jpDescripcion.add(jlblDescripcion5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 104, 340, 20));
        jpDescripcion.add(jlblDescripcion6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 134, 340, 20));

        jCheckBox1.setFont(new java.awt.Font("Arial", 1, 11));
        jCheckBox1.setText("OTRAS EMPRESAS");
        jCheckBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox1ActionPerformed(evt);
            }
        });

        jLabel24.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel24.setText("COMPR. PAGO"); // NOI18N

        jcboComprobante.setFont(new java.awt.Font("Arial", 0, 12)); // NOI18N

        eLProperty = org.jdesktop.beansbinding.ELProperty.create("${lista}");
        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, cboBeanBindingTipo1, eLProperty, jcboComprobante);
        bindingGroup.addBinding(jComboBoxBinding);

        jcboComprobante.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jcboComprobanteItemStateChanged(evt);
            }
        });
        jcboComprobante.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jcboComprobanteKeyPressed(evt);
            }
        });

        jLabel25.setFont(new java.awt.Font("Arial", 1, 11));
        jLabel25.setText("MONTO"); // NOI18N

        jtfMonto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtfMontoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(26, 26, 26)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jCheckBox1)
                                .addGap(121, 121, 121))
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jlblArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton1))
                                .addComponent(jLabel5)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                        .addComponent(jLabel24)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(jcboComprobante, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel1)
                                            .addComponent(jLabel20))
                                        .addGap(18, 18, 18)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(jtfOrden)
                                            .addComponent(jcbEmpresa, 0, 224, Short.MAX_VALUE)))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(jLabel2)
                                            .addComponent(jLabel25))
                                        .addGap(41, 41, 41)
                                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jtfFactura)
                                                .addGap(43, 43, 43)
                                                .addComponent(jLabel3)
                                                .addGap(10, 10, 10)
                                                .addComponent(jtfNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(jPanel1Layout.createSequentialGroup()
                                                .addComponent(jtfMonto, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(150, 150, 150))
                                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                                .addComponent(jftfFechaRegistro, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addGap(105, 105, 105))))))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(4, 4, 4)
                        .addComponent(jpDescripcion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jpDescripcion, javax.swing.GroupLayout.DEFAULT_SIZE, 163, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel20)
                    .addComponent(jcbEmpresa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jtfOrden, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel24)
                    .addComponent(jcboComprobante, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel25)
                    .addComponent(jtfMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jtfNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtfFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jftfFechaRegistro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jButton1)
                    .addComponent(jlblArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jbAceptar.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jbAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_ok.png"))); // NOI18N
        jbAceptar.setMnemonic('A');
        jbAceptar.setText("REGISTRAR");
        jbAceptar.setToolTipText("Registrar el Comprobante");
        jbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAceptarActionPerformed(evt);
            }
        });
        jbAceptar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbAceptarKeyPressed(evt);
            }
        });

        jbCancelar.setFont(new java.awt.Font("Arial", 1, 12));
        jbCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/iconoscomb/16x16ozygen/actions/button_cancel.png"))); // NOI18N
        jbCancelar.setMnemonic('C');
        jbCancelar.setText("CERRAR");
        jbCancelar.setToolTipText("Cancelar la Operacion");
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });
        jbCancelar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jbCancelarKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(85, 85, 85)
                        .addComponent(jbAceptar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbCancelar))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCancelar)
                    .addComponent(jbAceptar))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jftfFechaRegistroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jftfFechaRegistroActionPerformed
       // verificar();
        this.jbAceptar.requestFocus();
}//GEN-LAST:event_jftfFechaRegistroActionPerformed

    private void jbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAceptarActionPerformed
       String mensaje = verificar();
        if(mensaje.length()==0){
                int res = javax.swing.JOptionPane.showConfirmDialog( this,"Esta seguro de Guardar el Comprobante?",
                        "Confirmar",javax.swing.JOptionPane.YES_NO_OPTION );
                if(res==javax.swing.JOptionPane.YES_OPTION){
                    try {
                        TipoCambioDiario tipo;
                        try {
                             tipo=  GestionPedidosDelegate.getInstance().getTipoCambio(jftfFechaRegistro.getText().trim());
                            if(tipo==null){
                                 Utiles_MensajesDialogo.mensajeAlerta("El dia no tiene registrado un cambio de moneda!!");
                                 return;
                            }
                        } catch (Exception ex) {
                           ex.printStackTrace();
                        }
                        //Utiles_MensajesDialogo.mensajeInfo("Se guardo la Orden de Compra Correctamente");
                        BigDecimal monto = new BigDecimal(jtfMonto.getText().trim());

                        if((this.orden.getValor_total().subtract(this.orden.getMonto_cancelado())).compareTo(monto)>=0){
                            Parametros param = Listas.getParametrosID("SU1");
                            String ano = param.getParam1();
                            String mes = param.getParam2();
                            TipoTO tipo_forma_pago = Listas.getTipo_porId(this.orden.getForma_pago());
                            Tipo comprobante_tipo = Utiles_Convertir.convertirToTipo_TipoTO((TipoTO)jcboComprobante.getSelectedItem());

                            Date fecha_registro = new Date(VerificarDatos.verificaFecha(this.jftfFechaRegistro.getText()).getTime());
                            ComprobantePago cmt_pago = new ComprobantePago();
                            cmt_pago.setAno(ano);
                            cmt_pago.setMes(mes);
                            cmt_pago.setCodProveedor(this.orden.getRuc_proveedor());
                            cmt_pago.setCodTipoComprobante(comprobante_tipo);
                            cmt_pago.setSerieComprobante(this.jtfFactura.getText().trim());
                            cmt_pago.setNumeroComprobante(this.jtfNumero.getText().trim());
                            cmt_pago.setFechaIngreso(fecha_registro);
                            cmt_pago.setMonto_ingresado(BigDecimal.ZERO);
                            if(tipo_forma_pago.getCantidad() == null){
                                Utiles_MensajesDialogo.mensajeError("La forma de pago de la orden no posee cantidad de dias, Revise tipos ");
                                return;
                            }
                            cmt_pago.setFechaPago(Utiles_Fecha.sumarDias(fecha_registro, tipo_forma_pago.getCantidad().toBigInteger().intValue()));
                            cmt_pago.setUsuario(Propiedades.getUsuario());
                            cmt_pago.setMac(Propiedades.getMac());

                            cmt_pago.setArchivo(archivo);
                            cmt_pago.setMonto(monto);
                            if(GestionPedidosDelegate.getInstance().insertarComprobanteDeOrden(cmt_pago, this.orden.getNroOrden())){
                                Utiles_MensajesDialogo.mensajeInfo("Se registro el comprobante satisfactoriamente");
                                limpiar();
                                cargaHintsIndependientes();
                            }
                            else
                                 Utiles_MensajesDialogo.mensajeAlerta("Ya existe un comprobante con la misma serie y numero para el Proveedor");

                        }
                        else
                            Utiles_MensajesDialogo.mensajeAlerta("El monto del comprobante excede el monto disponible de la orden");

                    } catch (Exception e) {
                        e.printStackTrace();
                        Utiles_MensajesDialogo.mensajeError(">>"+e.getMessage());
                    }
                }
       }
        else{
            Utiles_MensajesDialogo.mensajeError(mensaje);
        }
    }//GEN-LAST:event_jbAceptarActionPerformed

    private void limpiar(){
        this.jtfOrden.setText("");
        this.jtfFactura.setText("");
        this.jtfNumero.setText("");
        this.jftfFechaRegistro.setText("");
        this.jtfMonto.setText("");
        this.jtfOrden.requestFocus();
        
        this.jlblDescripcion.setText("");
        this.jpDescripcion.setVisible(false);
        pack();
    }
    private void jbAceptarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbAceptarKeyPressed
        
}//GEN-LAST:event_jbAceptarKeyPressed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
        
        this.dispose();
}//GEN-LAST:event_jbCancelarActionPerformed

    private void jbCancelarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jbCancelarKeyPressed
        
}//GEN-LAST:event_jbCancelarKeyPressed

    private void jtfOrdenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfOrdenActionPerformed
        try {
           
            if(intelliHintsOrdenes.getSelectedHint()==null){
                orden = GestionPedidosDelegate.getInstance().isExisteOrden(this.jtfOrden.getText().trim());

                if(orden!=null){
                    this.isExisteOrden=true;
                    ProveedorTO pr = Listas.getProveedorcodigo(this.orden.getRuc_proveedor());
                    this.jlblDescripcion.setText("Zona: " + orden.getZona());
                    this.jlblDescripcion1.setText("Fecha Emision : " + orden.getFecha_emision());
                    this.jlblDescripcion2.setText("Proveedor : " + orden.getRuc_proveedor() + " - " + orden.getRazon_proveedor());
                    this.jlblDescripcion3.setText("Monto Total: " + orden.getValor_total().doubleValue());
                    this.jlblDescripcion4.setText("Monto Cancelado: " + orden.getMonto_cancelado().doubleValue());
                    this.jlblDescripcion6.setText("Tipo Moneda: " + orden.getMoneda_descripcion());
                    // TipoTO tp = Listas.getTipo_porId(this.orden.getTipo_comprobante());
                    // this.jlblTioComprobante.setText("COMPROBANTE : " +tp.getDescripcion_valor() + "Fecha de Emision : " + this.orden.getFecha_emision());
                }
                else{
                    this.isExisteOrden=false;
                    this.jtfOrden.requestFocus();
                    this.jtfFactura.setEnabled(false);
                    this.jlblDescripcion.setText("");

                }
            }
            else{
                   this.isExisteOrden=true;
                    orden = (OrdenTO)intelliHintsOrdenes.getSelectedHint();

                    this.jlblDescripcion.setText("Zona: " + orden.getZona());
                    this.jlblDescripcion1.setText("Fecha Emision : " + orden.getFecha_emision());
                    this.jlblDescripcion2.setText("Proveedor : " + orden.getRuc_proveedor() + " - " + orden.getRazon_proveedor());
                    this.jlblDescripcion3.setText("Monto Total: " + orden.getValor_total().doubleValue());
                    this.jlblDescripcion4.setText("Monto Cancelado: " + orden.getMonto_cancelado().doubleValue());
                    this.jlblDescripcion5.setText("Monto Disponible: " + (orden.getValor_total().subtract(orden.getMonto_cancelado())).doubleValue());
                    this.jlblDescripcion6.setText("Moneda: " + orden.getMoneda_descripcion());
                     this.jcboComprobante.requestFocus();
                        this.jtfFactura.setText("");
                        this.jtfNumero.setText("");
            }
        
            jpDescripcion.setVisible(true);
            pack();
           // verificar();
        } catch (Exception ex) {
            Logger.getLogger(jifRegistrarComprobanteDeOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jtfOrdenActionPerformed

    private void jtfFacturaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfFacturaActionPerformed
        //if(this.orden.)
      this.jtfNumero.requestFocus();
     
    }//GEN-LAST:event_jtfFacturaActionPerformed

    private void jtfOrdenKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtfOrdenKeyPressed
        
         if (evt.getKeyCode() != KeyEvent.VK_ENTER ){
            this.isExisteOrden=false;
            
        }
    }//GEN-LAST:event_jtfOrdenKeyPressed

    private void jtfNumeroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfNumeroActionPerformed
        this.jftfFechaRegistro.requestFocus();
        //this.jftfFechaRegistro.setEnabled(true);
       // verificar();
    }//GEN-LAST:event_jtfNumeroActionPerformed

    private void jftfFechaRegistroKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jftfFechaRegistroKeyPressed

    }//GEN-LAST:event_jftfFechaRegistroKeyPressed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        if(file==null) {
            file=new JFileChooser();
            filter = new ExampleFileFilter();
        }
            
         filter.addExtension("pdf");
         filter.setDescription("pdf ficheros");
         file.setAcceptAllFileFilterUsed(false);
         file.setFileFilter(filter);

         int option=file.showOpenDialog(null);
         if(option == JFileChooser.APPROVE_OPTION) {
			// obtiene nombre de archivo seleccionado
                File fobject = file.getSelectedFile();
            try {
                FileInputStream streamArchivo = new FileInputStream(fobject);
                archivo = new byte[(int) fobject.length()];
                streamArchivo.read(archivo);
                this.jlblArchivo.setText(fobject.getAbsolutePath());

           } catch (FileNotFoundException ex1) {
                Logger.getLogger(jifRegistrarComprobanteDeOrden.class.getName()).log(Level.SEVERE, null, ex1);

            } catch (IOException ex) {
                Logger.getLogger(jifRegistrarComprobanteDeOrden.class.getName()).log(Level.SEVERE, null, ex);

            }

	      	String filx= fobject.getPath();

        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jcbEmpresaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcbEmpresaItemStateChanged
        this.id_empresa = ((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getCodigo();
        try {
             List<OrdenTO> lista = GestionPedidosDelegate.getInstance().getOrdenesSinComprobante(Listas.getZonas(), this.id_empresa);
             this.intelliHintsOrdenes.setCompletionList(lista);
        } catch (Exception ex) {
            ex.printStackTrace();
            Logger.getLogger(jifRegistrarComprobanteDeOrden.class.getName()).log(Level.SEVERE, null, ex);
        }
}//GEN-LAST:event_jcbEmpresaItemStateChanged

    private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox1ActionPerformed
        if(this.jCheckBox1.isSelected()){
            this.jcbEmpresa.setEnabled(true);
        } else{
            this.jcbEmpresa.setEnabled(false);
        }
        this.llenarComboEmpresa();
        //this.intelliHintsProyectos.setCompletionList(Listas.obtenerProyectosPorEmpresa(((EmpresaTO)this.jcbEmpresa.getSelectedItem()).getRuc()));
}//GEN-LAST:event_jCheckBox1ActionPerformed

    private void jcboComprobanteItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jcboComprobanteItemStateChanged

    }//GEN-LAST:event_jcboComprobanteItemStateChanged

    private void jcboComprobanteKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jcboComprobanteKeyPressed
        jtfMonto.requestFocus();
        
}//GEN-LAST:event_jcboComprobanteKeyPressed

    private void jtfMontoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtfMontoActionPerformed
        jtfFactura.requestFocus();
    }//GEN-LAST:event_jtfMontoActionPerformed

    private void verificarOrden(){

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private administracion.BeanBinding.CboBeanBindingEmpresa cboBeanBindingEmpresa1;
    private administracion.BeanBinding.CboBeanBindingTipo cboBeanBindingTipo1;
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel25;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton jbAceptar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JComboBox jcbEmpresa;
    private javax.swing.JComboBox jcboComprobante;
    private javax.swing.JFormattedTextField jftfFechaRegistro;
    private javax.swing.JLabel jlblArchivo;
    private javax.swing.JLabel jlblDescripcion;
    private javax.swing.JLabel jlblDescripcion1;
    private javax.swing.JLabel jlblDescripcion2;
    private javax.swing.JLabel jlblDescripcion3;
    private javax.swing.JLabel jlblDescripcion4;
    private javax.swing.JLabel jlblDescripcion5;
    private javax.swing.JLabel jlblDescripcion6;
    private javax.swing.JPanel jpDescripcion;
    private javax.swing.JTextField jtfFactura;
    private javax.swing.JTextField jtfMonto;
    private javax.swing.JTextField jtfNumero;
    private javax.swing.JTextField jtfOrden;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public void asignaEntidadEncontrada(SimpleEntidadTO elemento) {
        jpDescripcion.setVisible(true);
        pack();
        this.jtfOrden.setText(elemento.getCodigo());
        this.jlblDescripcion.setText(elemento.getDescripcion());
    }

}
